const db = require('./db')

const comment = {
    async create({ postId, userId, content }) {
        const [result] = await db.query(
            `INSERT INTO comments (post_id, user_id, content) 
           VALUES (?, ?, ?)`,
            [postId, userId, content]
        );
        return this.findById(result.insertId);
    },

    async findById(id) {
        const [rows] = await db.query(
            `SELECT * FROM comments WHERE id = ?`,
            [id]
        );
        return rows[0];
    },

    async findByPostId(postId, page = 1, limit = 10) {
        const offset = (page - 1) * limit;
        const [rows] = await db.query(
            `SELECT 
            c.*, 
            u.username AS user_name
        FROM comments c
        LEFT JOIN users u ON c.user_id = u.user_id
        WHERE c.post_id = ?
        ORDER BY c.created_at DESC
        LIMIT ? OFFSET ?`,
            [postId, limit, offset]
        );
        return rows;
    },

    async updateContent(id, newContent) {
        await db.query(
            `UPDATE comments SET content = ? WHERE id = ?`,
            [newContent, id]
        );
        return this.findById(id);
    },

    // 增加点赞数
    async incrementLikes(id) {
        await db.query(
            `UPDATE comments 
       SET likes = likes + 1 
       WHERE id = ?`,
            [id]
        );
        return this.findById(id);
    },

    // 减少点赞数
    async decrementLikes(id) {
        await db.query(
            `UPDATE comments 
       SET likes = GREATEST(likes - 1, 0) 
       WHERE id = ?`,
            [id]
        );
        return this.findById(id);
    },

    async delete(id) {
        await db.query(
            `DELETE FROM comments WHERE id = ?`,
            [id]
        );
        return true;
    },

    async countByPostId(postId) {
        const [rows] = await db.query(
            `SELECT COUNT(*) AS total FROM comments 
       WHERE post_id = ?`,
            [postId]
        );
        return rows[0].total;
    }
}

module.exports = comment;